package com.zjq.jwt;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;


/**
 * @author zjq
 * @date 2020/3/17 10:34
 * <p>title:jwt拦截器</p>
 * <p>company:zjhcsoft</p>
 * <p>description:通过拦截器实现统一鉴权</p>
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String userId = request.getHeader("account");
        JSONObject json = new JSONObject();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //判断token是否为空
        if(!StrUtil.isEmpty(token)){
            //解析token
            Claims claims = jwtUtil.parseJwt(token);
            if(claims==null){
                PrintWriter printWriter = response.getWriter();
                json.put("success", ResponseCode.TOKENTIMEOUT.success());
                json.put("code", ResponseCode.TOKENTIMEOUT.code());
                json.put("message", ResponseCode.TOKENTIMEOUT.message());
                json.put("result", null);
                printWriter.write(json.toJSONString());
            }
            Long date = claims.getExpiration().getTime();
            Long now = System.currentTimeMillis();
            if(now>date){
                PrintWriter printWriter = response.getWriter();
                json.put("success", ResponseCode.TOKENTIMEOUT.success());
                json.put("code", ResponseCode.TOKENTIMEOUT.code());
                json.put("message", ResponseCode.TOKENTIMEOUT.message());
                json.put("result", null);
                printWriter.write(json.toJSONString());
            }
            return true;
        }
        PrintWriter printWriter = response.getWriter();
        json.put("success", ResponseCode.UNAUTHENTICATED.success());
        json.put("code", ResponseCode.UNAUTHENTICATED.code());
        json.put("message", ResponseCode.UNAUTHENTICATED.message());
        json.put("result", null);
        printWriter.write(json.toJSONString());
        return false;
    }

}
